package com.xgggh.redpack.ui.redpack;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.jakewharton.rxbinding3.view.RxView;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.xgggh.redpack.R;
import com.xgggh.redpack.base.ui.BaseActivity;
import com.xgggh.redpack.databinding.ActivityRedPackBinding;
import com.xgggh.redpack.domain.app.IntentFlag;
import com.xgggh.redpack.domain.category.CategoryItem;
import com.xgggh.redpack.domain.redpack.Pack;
import com.xgggh.redpack.domain.redpack.PackBinding;
import com.xgggh.redpack.ui.map.MapActivity;
import javax.inject.Inject;

import dagger.android.AndroidInjection;
import io.reactivex.functions.Consumer;
import io.reactivex.subscribers.DisposableSubscriber;
import model.Loading;
import model.Rsp;
import model.Status;
import viewmodel.RedPackViewModel;
import viewmodel.ViewModelFactory;


public class RedPackActivity extends BaseActivity implements BDLocationListener {
    ActivityRedPackBinding mBinding;
    CategoryItem categoryItem;


    protected final int MY_PERMISSIONS_REQUEST=200;

    LocationClient locationClient;
    @Inject
    ViewModelFactory factory;
    RedPackViewModel model= null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        categoryItem=(CategoryItem)getIntent().getSerializableExtra(IntentFlag.data);
        if (categoryItem==null){
            Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show();
            finish();
        }
        mBinding= DataBindingUtil.setContentView(this,R.layout.activity_red_pack);
        setSupportActionBar(mBinding.toolbar.toolbar);
        mBinding.contentRedPack.twinklingRefreshLayout.setPureScrollModeOn();
        model= ViewModelProviders.of(this,factory).get(RedPackViewModel.class);


        mBinding.setItem(new PackBinding());
        mBinding.getItem().setCategory(categoryItem.getType());
        mBinding.setLoad(new Loading());

        mBinding.contentRedPack.amount.setSelection(0);
        //mBinding.contentRedPack.fee.setSelection(mBinding.contentRedPack.fee.getHint().length());
        onClickListener();

     /*   if(getBaseContext().checkSelfPermission(Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            requestPermissions( new String[]{ Manifest.permission.READ_PHONE_STATE },BAIDU_READ_PHONE_STATE );
        }*/
        mayRequestPermissions(new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        },MY_PERMISSIONS_REQUEST);
        initLocationOption();
    }


    /**
     * 初始化定位参数配置
     */

    private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        //MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerNotifyLocationListener(this);
//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        //locationOption.setCoorType("gcj02");
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(1000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
//可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(true);
//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
//可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(3000,1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
//开始定位
        locationClient.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,grantResults);
        switch(requestCode) {
            //requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case MY_PERMISSIONS_REQUEST:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //获取到权限，做相应处理
                    //调用定位SDK应确保相关权限均被授权，否则会引起定位失败
                    locationClient.restart();
                } else{
                    //没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }
    protected void onClickListener(){
        RxView.clicks(mBinding.contentRedPack.send)
                .compose(uiTransformer())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        createRedPack(mBinding.getItem());
                       // Toast.makeText(RedPackActivity.this, mBinding.getRedPack().getFee(), Toast.LENGTH_SHORT).show();
                           // startActivity(new Intent(mBinding.contentRedPack.send.getContext(), PayActivity.class));
                    }
                });

        RxView.clicks(mBinding.contentRedPack.location)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivity(new Intent(mBinding.contentRedPack.send.getContext(), MapActivity.class));
                    }
                });


        RxView.clicks(mBinding.contentRedPack.time)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Toast.makeText(RedPackActivity.this, "时间选择", Toast.LENGTH_SHORT).show();
                        //startActivity(new Intent(mBinding.contentRedPack.send.getContext(), MapActivity.class));
                    }
                });
    }

    @Inject
    Gson gson;

    private void createRedPack(PackBinding packBinding){
        Pack pack= gson.fromJson(gson.toJson(packBinding),Pack.class);
        mBinding.getLoad().setStatus(Loading.LOADING);
        model.createRedPack(pack)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(getLifecycle())))
                .subscribe(new DisposableSubscriber<Rsp<Pack>>() {
          @Override
          public void onNext(Rsp<Pack> rsp) {
              if (rsp.status== Status.OK){
                  Toast.makeText(RedPackActivity.this, "红包发布成功", Toast.LENGTH_SHORT).show();
                  finish();
              }else if (rsp.status== Status.ERROR){
                  Toast.makeText(getBaseContext(),rsp.getMsg(), Toast.LENGTH_SHORT).show();
              }
          }

          @Override
          public void onError(Throwable t) {
              Toast.makeText(getBaseContext(),t.getMessage(), Toast.LENGTH_SHORT).show();
          }

          @Override
          public void onComplete() {
              mBinding.getLoad().setStatus(Loading.FINISH);
          }
      });
    }



    @Override
    public void onReceiveLocation(BDLocation location) {
        if (location == null ) {
            return;
        }
        String address=(TextUtils.isEmpty(location.getCity())?"":location.getCity())
                +(TextUtils.isEmpty(location.getDistrict())?"":location.getDistrict())
                +(TextUtils.isEmpty(location.getStreet())?"":location.getStreet())
                +(TextUtils.isEmpty(location.getStreetNumber())?"":location.getStreetNumber());
        //mBinding.getItem().setAddress(address);
       /* mapBinding.setAddressPOI(location.getAddress().address);
        mCurrentLat = location.getLatitude();
        mCurrentLon = location.getLongitude();
        mapBinding.setLocation(mCurrentLat+","+mCurrentLon);*/
        mBinding.getItem().setAddress(address);
        mBinding.getItem().setLatitude(location.getLatitude());
        mBinding.getItem().setLongitude(location.getLongitude());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 退出时销毁定位
        if (locationClient!=null){
            locationClient.stop();
        }
    }


}
